import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutterapp/Base/EventBus/Events.dart';
import 'package:flutterapp/Base/methodChannel/MethodChannelManager.dart';
import 'package:flutterapp/Base/style/MyStyles.dart';

class PageSocketTest extends StatefulWidget {
  static const ROUTER_NAME = "PageSocketTest";

  @override
  _PageSocketTestState createState() => _PageSocketTestState();
}

class _PageSocketTestState extends State<PageSocketTest> {
  List<String> eventList = [];
  TextEditingController controller = new TextEditingController();
  StreamSubscription<EventOnSocketMsg> subscription;
  static const wsUri = "ws://192.168.31.216:8082/ws/testsocket";

  @override
  void initState() {
    super.initState();
    controller.text = "";

    subscription = myEventBus.on<EventOnSocketMsg>().listen((event) {
      eventList.add("rec: ${event.msg}");
      setState(() {});
    });
  }

  @override
  void dispose() {
    subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        child: Column(
          children: [
            Expanded(
              child: Container(
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    return Text("${eventList[index]}",style: MyTextStyle.WHITE_14,);
                  },
                  itemCount: eventList.length,
                ),
                color: Colors.black,
              ),
            ),
            TextField(
              controller: controller,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                MaterialButton(
                  child: Text("disconnect"),
                  onPressed: () {
                    MethodChannelManager.getInstance()
                        .invoke(MethodTypes.SOCKET_CLOSE);
                  },
                ),
                MaterialButton(
                  child: Text("send"),
                  onPressed: () {
                    MethodChannelManager.getInstance()
                        .invoke(MethodTypes.SOCKET_SEND_MSG, controller.text);
                    eventList.add("send: ${controller.text}");
                    controller.text = "";
                    setState(() {});
                  },
                ),
                MaterialButton(
                  child: Text("connect"),
                  onPressed: () {
                    eventList.clear();
                    MethodChannelManager.getInstance()
                        .invoke(MethodTypes.SOCKET_CREATE, wsUri);
                  },
                )
              ],
            )
          ],
        ),
      ),
    );
  }
}
